package com.profiloc.ui.screens;

import java.util.Date;
import java.util.Vector;

import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.system.ApplicationManagerException;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.CodeModuleManager;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.ContextMenu;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;

import com.profiloc.model.Profile;
import com.profiloc.ui.custom.FontColorField;
import com.profiloc.util.LocationHandler;

public class ProfileListScreen extends ListField implements ListFieldCallback
{
   
	private Profile profile;
    private Vector rows;
    private Bitmap p0;
    private Bitmap p1;
    private Bitmap p2;
    private Bitmap p3;
    private Bitmap p4;
    private Bitmap p5;
    private static Vector profiles;
	private PersistentObject profilePersist;

    
    public ProfileListScreen(MainMenuScreen mainScreen)
    {
    	
        super(0, ListField.MULTI_SELECT);
        profilePersist = PersistentStore.getPersistentObject(0x4e73ce89227e0b61L);
        
        synchronized (profilePersist) {
        	profiles = (Vector) profilePersist.getContents();
        	
		}
        
        setEmptyString("Uuppss!!, no profiles here!", DrawStyle.HCENTER);
        
        if(profiles != null){
        	
        	setEmptyString("Uuppss!!, no profiles here!", DrawStyle.HCENTER);
 	     	
         	setRowHeight(45);
            setCallback(this);
             
             p0 = Bitmap.getBitmapResource("home.png");
             p1 = Bitmap.getBitmapResource("computer.png");
             p2 = Bitmap.getBitmapResource("university.png");
             p3 = Bitmap.getBitmapResource("workoffice.png");
             
             rows = new Vector();
            
             for(int x = 0; x < profiles.size(); ++x)
             {
                 TableRowManager row = new TableRowManager();
                 profile = (Profile) profiles.elementAt(x);

                 // SET THE PRIORITY BITMAP FIELD
                 // if high priority, display p1 bitmap
                 if(x % 4 == 0)
                 {
                     row.add(new BitmapField(p0));
                 }
                 // if priority is 2, set p2 bitmap
                 else if(x % 4 == 1)
                 {
                     row.add(new BitmapField(p1));
                 }
                 // if priority is 3, set p3 bitmap
                 else if(x % 4 == 2)
                 {
                     row.add(new BitmapField(p2));
                 }
                 // no priority set
                 else if(x % 4 == 3)
                 {
                     row.add(new BitmapField(p3));
                 }

                
                 // SET THE TASK NAME LABELFIELD
                 // if overdue, bold/underline
                 LabelField task = new LabelField(profile.getName(), DrawStyle.ELLIPSIS);
                 // if due today, bold
                 /*if(profile.getUseSmartPhonebook())
                 {
                     task.setFont(Font.getDefault().derive(Font.BOLD | Font.UNDERLINED));
                 }
                 else 
                 {*/
                     task.setFont(Font.getDefault().derive(Font.BOLD));
                 //}
                
                 row.add(task);
                
                 // SET THE LIST NAME
                 row.add(new FontColorField(profile.getName(), DrawStyle.ELLIPSIS, 0x00878787));
                
                 // SET THE DUE DATE/TIME
                 row.add(new FontColorField(new Date(profile.getStartTime()).toString(), DrawStyle.ELLIPSIS | LabelField.USE_ALL_WIDTH | DrawStyle.RIGHT, 0x00878787));
                
                 rows.addElement(row);
             }
            
             setSize(rows.size());  
        }
       

        
    }      
   
    private class TableRowManager extends Manager
    {
        public TableRowManager()
        {
            super(0);
        }
       
        // Causes the fields within this row manager to be layed out then
        // painted.
        public void drawRow(Graphics g, int x, int y, int width, int height)
        {
            // Arrange the cell fields within this row manager.
            layout(width, height);

            // Place this row manager within its enclosing list.
            setPosition(x, y);

            // Apply a translating/clipping transformation to the graphics
            // context so that this row paints in the right area.
            g.pushRegion(getExtent());

            // Paint this manager's controlled fields.
            subpaint(g);
           
            g.setColor(0x00CACACA);
            g.drawLine(0, 0, getPreferredWidth(), 0);
            g.drawLine(30, 0, 30, getPreferredHeight());
           

            // Restore the graphics context.
            g.popContext();
        }
       
        // Arrages this manager's controlled fields from left to right within
        // the enclosing table's columns.
        protected void sublayout(int width, int height)
        {
            // set the size and position of each field.
            int fontHeight = Font.getDefault().getHeight();
            int preferredWidth = getPreferredWidth();
           
            // start with the Bitmap Field of the priority icon
            Field field = getField(0);
            layoutChild(field, 30, 40);
            setPositionChild(field, 0, 0);
           
            // set the task name label field
            field = getField(1);
            layoutChild(field, preferredWidth - 16, fontHeight+1);
            setPositionChild(field, 40, 3);
                       
            // set the list name label field
            field = getField(2);
            layoutChild(field, 150, fontHeight+1);
            setPositionChild(field, 40, fontHeight+2);
           
            // set the due time name label field
            field = getField(3);
            layoutChild(field, 150, fontHeight+1);
            setPositionChild(field, preferredWidth - 152, fontHeight+2);

            setExtent(preferredWidth, getPreferredHeight());
        }
       
        // The preferred width of a row is defined by the list renderer.
        public int getPreferredWidth()
        {
            return Display.getWidth();
        }

        // The preferred height of a row is the "row height" as defined in the
        // enclosing list.
        public int getPreferredHeight()
        {
            return getRowHeight();
        }
    }

    // ListFieldCallback Implementation
    public void drawListRow(ListField listField, Graphics g, int index, int y, int width)
    {
        ProfileListScreen list = (ProfileListScreen) listField;
        TableRowManager rowManager = (TableRowManager)list.rows.elementAt(index);
        rowManager.drawRow(g, 0, y, width, list.getRowHeight());
    }
   
    public Object get(ListField list, int index)
    {
        return profiles.elementAt(index);
    }
   
    public int indexOfList(ListField list, String p, int s)
    {
        return -1;
    }
   
    public int getPreferredWidth(ListField list)
    {
        return Display.getWidth();
    }
   
    public ContextMenu getContextMenu()
    {
        ContextMenu menu = super.getContextMenu();

        menu.addItem(new EditTaskMenuItem());
        menu.addItem(new DeleteTaskMenuItem());
        menu.addItem(new ActivateMenuItem());
        
        return menu;        
    }
   
    protected boolean trackwheelClick(int status, int time)
    {
       
        return true;
    }
   
    public void delete(int index)
    {
        rows.removeElementAt(index);
        profiles.removeElementAt(index);
        super.delete(index);
        /*
         * commit persistance data to not restore object
         * again after reset
         */
        profilePersist.commit();
    }
   
    private final class EditTaskMenuItem extends MenuItem
    {
        public EditTaskMenuItem()
        {
            super("Edit", 100001, 2);
        }
       
        public void run()
        {
            int index = getSelectedIndex();
            Profile editedProfile = (Profile) profiles.elementAt(index);
            ProfileSettingsScreen editSettingsScreen = new ProfileSettingsScreen(editedProfile,index);
            UiApplication.getUiApplication().pushScreen(editSettingsScreen);        
        }
    }
   
    private final class DeleteTaskMenuItem extends MenuItem
    {
        public DeleteTaskMenuItem()
        {
            super("Delete", 100002, 3);
        }
       
        public void run()
        {
            int index = getSelectedIndex();
           
            delete(index);
            Dialog.alert("Deleted successfully...");
        }
    }
    private final class ActivateMenuItem extends MenuItem{
    	
    	int index = getSelectedIndex();
    	Profile profile = (Profile) profiles.elementAt(index);
    	public ActivateMenuItem() {
			// TODO Auto-generated constructor stub
    		super("Activate", 100003, 4);
		}
    	
    	public void run() {
    		// TODO Auto-generated method stub
    		//call to the listener 
    		Dialog.ask(Dialog.D_OK, "Activating the profile     \t\t\""+ profile.getName() +"\"\nSelect volume level \tfor this profile.");
    		openProfiles();
    		
    		LocationHandler handler = new LocationHandler(null, true,45,index);
    		
    		handler.start();
    	}
    	
    	 private void openProfiles() {
    		  int handle = CodeModuleManager.getModuleHandle("net_rim_bb_profiles_app");
    		  ApplicationDescriptor[] appDescr = CodeModuleManager
    		    .getApplicationDescriptors(handle);
    		 if (appDescr.length > 0) {
    		   try {
    		    ApplicationManager.getApplicationManager().runApplication(
    		      appDescr[0]);
    		   	} catch (ApplicationManagerException e) {
    		    // TODO Auto-generated catch block
    		    e.printStackTrace();
    		   }
    		 }
    		 UiApplication.getUiApplication().requestBackground();
    	}	 
    }
}

